<?php
namespace app\shop\controller;

use think\Db;
use think\Loader;
use think\Request;
use think\Controller;
use app\shop\model\MemberOrder as MemberOrderModel;
use app\shop\model\AuctionOrder as AuctionOrderModel;
use app\shop\model\MemberWithdraw as MemberWithdrawModel;

class WeChat extends Controller
{

    public function pay()
    {
        // halt($_SERVER);
        // Loader::import('wxpay/lib/WxPay.Api.php');
        // Loader::import('wxpay/lib/WxPay.NativePay.php');
        // Loader::import('wxpay/lib/log.php');

        require EXTEND_PATH . 'wxpay/web/lib/WxPay.Api.php';
        require EXTEND_PATH . 'wxpay/web/WxPay.NativePay.php';
        require EXTEND_PATH . 'wxpay/web/log.php';
        $orderNumber = Request::instance()->param('order_number');

        //付款金额，必填
        $price_fee = (new MemberOrderModel)->where('order_number|shop_order_number',$orderNumber)->sum('price');
        $freight_fee = (new MemberOrderModel)->where('order_number|shop_order_number',$orderNumber)->sum('freight');
        $price = bcadd($price_fee,$freight_fee,2);
        $total_fee = $price*100;

        //商品描述，可空
        $body = Request::instance()->param('body');

        // 异步地址
        $notify_url = Request::instance()->domain() . \think\Url::build('interfaces/WxPay/notifyurl');

        // 回调地址
        $return_url = Request::instance()->domain() . \think\Url::build('shop/member_order/index');
        // 商品ID
        $goodsId = Request::instance()->param('goods_id');
        //模式二
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */
        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("Ishop微信支付");
        $input->SetAttach($body);
        $input->SetOut_trade_no($orderNumber);
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($goodsId);

        $result = $notify->GetPayUrl($input);
      
        $url2 = $result["code_url"];
        return $this->fetch('', [
            'order' => $orderNumber,
            'url' => $url2,
            'web' => isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http'  . "://" . $_SERVER['HTTP_HOST'],
            'return_url' => 1,
        ]);
    }


    /**
     * 微信支付充值
     */
    public function rechange()
    {
        require EXTEND_PATH . 'wxpay/web/lib/WxPay.Api.php';
        require EXTEND_PATH . 'wxpay/web/WxPay.NativePay.php';
        require EXTEND_PATH . 'wxpay/web/log.php';
        $orderNumber = Request::instance()->param('order_number');
        $price = Request::instance()->param('price');
        //付款金额，必填

        $total_fee = $price*100;

        //商品描述，可空
        $body = Request::instance()->param('body');

        // 异步地址
        $notify_url = Request::instance()->domain() . \think\Url::build('interfaces/WxPay/notifyurl');

        // 回调地址
        // $return_url = Request::instance()->domain() . \think\Url::build('shop/member_wallet/rechrage');
        // 商品ID
        $goodsId = Request::instance()->param('goods_id',rand());
        //模式二
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */
        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("Ishop微信支付");
        $input->SetAttach($body);
        $input->SetOut_trade_no($orderNumber);
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($goodsId);
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];


        return $this->fetch('we_chat_pay', [
            'order' => $orderNumber,
            'url' => $url2,
            'web' => isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http'  . "://" . $_SERVER['HTTP_HOST'],
            'return_url' => 2,
        ]);
    }

    public function auction()
    {
        require EXTEND_PATH . 'wxpay/web/lib/WxPay.Api.php';
        require EXTEND_PATH . 'wxpay/web/WxPay.NativePay.php';
        require EXTEND_PATH . 'wxpay/web/log.php';
        $orderNumber = Request::instance()->param('order_number');
        //付款金额，必填
        $price = (new AuctionOrderModel())->where('order_number',$orderNumber)->value('price');
        $total_fee = $price*100;

        //商品描述，可空
        $body = Request::instance()->param('body');

        // 异步地址
        $notify_url = Request::instance()->domain() . \think\Url::build('interfaces/WxPay/notifyurl');

        // 回调地址
        // $return_url = Request::instance()->domain() . \think\Url::build('shop/member_wallet/rechrage');
        // 商品ID
        $goodsId = Request::instance()->param('goods_id',rand());
        //模式二
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */
        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("喜利在线支付");
        $input->SetAttach($body);
        $input->SetOut_trade_no($orderNumber);
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($goodsId);
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];


        return $this->fetch('we_chat_pay', [
            'order' => $orderNumber,
            'url' => $url2,
            'web' => isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http'  . "://" . $_SERVER['HTTP_HOST'],
            'return_url' => 2,
        ]);
    }





    public function or_code()
    {
        $data = Request::instance()->param('data');
        Loader::import('phpqrcode.phpqrcode', EXTEND_PATH);
        $url = base64_decode($data);
        \QRcode::png($url);
    }


    /**
     * 微信查询订单状态是否改变
     */
    public function check_order()
    {
        // 获取订单号
        $orderNumber = Request::instance()->param('order');

        // 获取订单状态
        $status = Db::name('member_order')->where('order_number|shop_order_number',$orderNumber)->value('status');

        if ($status==1) {
            return ['code'=>200];
        }else {
            return ['code'=>402];
        }
    }


    /**
     * 微信充值状态是否改变
     */
    public function check_charge()
    {
        // 获取订单号
        $orderNumber = Request::instance()->param('order');

        // 查看订单状态
        $status = Db::name('member_withdraw')->where('order_number',$orderNumber)->value('status');

        if ($status==1) {
            return ['code'=>200];
        }else {
            return ['code'=>402];
        }
    }
}